<template>
  <view class="register-container">
    <!-- 原生表单容器 -->
    <view class="form-wrap">
      <!-- 用户名 -->
      <view class="form-item">
        <text class="form-label">用户名</text>
        <input 
          v-model="formData.username" 
          class="form-input" 
          placeholder="请输入4-20位用户名"
          maxlength="20"
          @input="handleInput"
        ></input>
        <text class="error-tip" v-if="errorMsg.username">{{ errorMsg.username }}</text>
      </view>

      <!-- 密码 -->
      <view class="form-item">
        <text class="form-label">密码</text>
        <input 
          v-model="formData.password" 
          class="form-input" 
          placeholder="请输入至少6位密码"
          password
          maxlength="20"
          @input="handleInput"
        ></input>
        <text class="error-tip" v-if="errorMsg.password">{{ errorMsg.password }}</text>
      </view>

      <!-- 确认密码 -->
      <view class="form-item">
        <text class="form-label">确认密码</text>
        <input 
          v-model="formData.confirmPwd" 
          class="form-input" 
          placeholder="请再次输入密码"
          password
          maxlength="20"
          @input="handleInput"
        ></input>
        <text class="error-tip" v-if="errorMsg.confirmPwd">{{ errorMsg.confirmPwd }}</text>
      </view>

      <!-- 昵称（可选） -->
      <view class="form-item">
        <text class="form-label">昵称</text>
        <input 
          v-model="formData.nickname" 
          class="form-input" 
          placeholder="请输入昵称（选填）"
          maxlength="10"
        ></input>
      </view>

      <!-- 性别（可选） -->
      <view class="form-item">
        <text class="form-label">性别</text>
        <view class="gender-wrap">
          <label class="gender-label" v-for="item in genderOptions" :key="item.value">
            <radio 
              v-model="formData.gender" 
              :value="item.value"
              color="#007aff"
            ></radio>
            <text>{{ item.text }}</text>
          </label>
        </view>
      </view>

      <!-- 手机号（可选） -->
      <view class="form-item">
        <text class="form-label">手机号</text>
        <input 
          v-model="formData.phone" 
          class="form-input" 
          placeholder="请输入11位手机号（选填）"
          type="number"
          maxlength="11"
          @input="handleInput"
        ></input>
        <text class="error-tip" v-if="errorMsg.phone">{{ errorMsg.phone }}</text>
      </view>

      <!-- 邮箱（可选） -->
      <view class="form-item">
        <text class="form-label">邮箱</text>
        <input 
          v-model="formData.email" 
          class="form-input" 
          placeholder="请输入邮箱（选填）"
          @input="handleInput"
        ></input>
        <text class="error-tip" v-if="errorMsg.email">{{ errorMsg.email }}</text>
      </view>

      <!-- 注册按钮 -->
      <button 
        class="submit-btn" 
        @click="submitForm" 
        :loading="isSubmitting"
      >
        注册
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';

// 1. 表单数据
const formData = ref({
  username: '',
  password: '',
  confirmPwd: '',
  nickname: '',
  gender: 0, // 0未知 1男 2女
  phone: '',
  email: ''
});

// 2. 错误提示信息
const errorMsg = ref({
  username: '',
  password: '',
  confirmPwd: '',
  phone: '',
  email: ''
});

// 3. 加载状态
const isSubmitting = ref(false);

// 4. 性别选项
const genderOptions = [
  { text: '未知', value: 0 },
  { text: '男', value: 1 },
  { text: '女', value: 2 }
];

// 5. 表单校验规则（自定义函数，无依赖）
const validateForm = () => {
  let isValid = true;
  // 重置错误提示
  errorMsg.value = {
    username: '',
    password: '',
    confirmPwd: '',
    phone: '',
    email: ''
  };

  // 用户名校验
  if (!formData.value.username.trim()) {
    errorMsg.value.username = '请输入用户名';
    isValid = false;
  } else if (formData.value.username.length < 4 || formData.value.username.length > 20) {
    errorMsg.value.username = '用户名长度为4-20位';
    isValid = false;
  }

  // 密码校验
  if (!formData.value.password.trim()) {
    errorMsg.value.password = '请输入密码';
    isValid = false;
  } else if (formData.value.password.length < 6) {
    errorMsg.value.password = '密码长度至少6位';
    isValid = false;
  }

  // 确认密码校验
  if (formData.value.confirmPwd !== formData.value.password) {
    errorMsg.value.confirmPwd = '两次密码不一致';
    isValid = false;
  }

  // 手机号校验（可选，填了才校验）
  if (formData.value.phone && !/^1[3-9]\d{9}$/.test(formData.value.phone)) {
    errorMsg.value.phone = '手机号格式错误';
    isValid = false;
  }

  // 邮箱校验（可选，填了才校验）
  if (formData.value.email && !/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(formData.value.email)) {
    errorMsg.value.email = '邮箱格式错误';
    isValid = false;
  }

  return isValid;
};

// 6. 输入事件（实时清除错误提示）
const handleInput = () => {
  errorMsg.value = {
    username: '',
    password: '',
    confirmPwd: '',
    phone: '',
    email: ''
  };
};

// 7. 提交表单（对接云函数）
const submitForm = async () => {
  if (isSubmitting.value) return;

  // 1. 前端表单校验
  if (!validateForm()) {
    return;
  }

  isSubmitting.value = true;

  try {
    // 2. 构造云函数参数（移除confirmPwd，只传Schema需要的字段）
    const submitData = {
      username: formData.value.username.trim(),
      password: formData.value.password.trim(),
      nickname: formData.value.nickname.trim() || '默认昵称',
      gender: formData.value.gender,
      phone: formData.value.phone.trim() || '',
      email: formData.value.email.trim() || ''
    };

    // 3. 调用云函数（核心：对接addUser云函数）
    const res = await uniCloud.callFunction({
      name: 'addUser', // 替换为你的云函数实际名称！
      data: submitData,
      timeout: 5000 // 5秒超时保护
    });

    // 4. 处理云函数返回结果
    const { code, msg } = res.result;
    if (code === 0) {
      uni.showToast({
        title: msg || '注册成功！',
        icon: 'success',
        duration: 2000
      });
      // 注册成功后清空表单
      formData.value = {
        username: '',
        password: '',
        confirmPwd: '',
        nickname: '',
        gender: 0,
        phone: '',
        email: ''
      };
    } else {
      uni.showToast({
        title: msg || '注册失败',
        icon: 'none',
        duration: 2000
      });
    }
  } catch (err) {
    // 捕获云函数调用失败（网络/超时/云函数报错）
    uni.showToast({
      title: '网络异常，请重试',
      icon: 'none',
      duration: 2000
    });
    console.error('云函数调用失败：', err); // 调试用，上线前删除
  } finally {
    // 无论成功/失败，都重置加载状态
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
/* 页面容器 */
.register-container {
  padding: 30rpx 20rpx;
  width: 100%;
  box-sizing: border-box;
}

/* 表单容器 */
.form-wrap {
  width: 100%;
  max-width: 600rpx;
  margin: 0 auto;
}

/* 表单项 */
.form-item {
  margin-bottom: 30rpx;
  width: 100%;
}

/* 表单标签 */
.form-label {
  display: inline-block;
  width: 100rpx;
  font-size: 28rpx;
  color: #333;
  margin-right: 20rpx;
}

/* 输入框 */
.form-input {
  width: calc(100% - 120rpx);
  height: 70rpx;
  border: 1px solid #eee;
  border-radius: 35rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

/* 错误提示 */
.error-tip {
  display: block;
  margin-left: 120rpx;
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #ff3b30;
}

/* 性别选项 */
.gender-wrap {
  display: inline-block;
  width: calc(100% - 120rpx);
}

.gender-label {
  margin-right: 30rpx;
  font-size: 28rpx;
  color: #666;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #007aff;
  color: #fff;
  border-radius: 40rpx;
  font-size: 32rpx;
  margin-top: 20rpx;
}
</style>